﻿
using Microsoft.Extensions.Configuration;

namespace Micro.Core.Configs
{
    public class AppsettingConfigs
    {
        public static string ConfigsDir => GetDirPathOrCreate("Configs");
        static IConfiguration Configuration { get; set; }


        public AppsettingConfigs(IConfiguration configuration)
        {
            Configuration = configuration;
        }


        /// <summary>
        /// 封装要操作的字符
        /// </summary>
        /// <param name="sections">节点配置</param>
        /// <returns></returns>
        public static string app(params string[] sections)
        {
            try
            {

                if (sections.Any())
                {
                    return Configuration[string.Join(":", sections)];
                }
            }
            catch (Exception) { }

            return "";
        }

        /// <summary>
        /// 递归获取配置信息数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sections"></param>
        /// <returns></returns>
        public static List<T> app<T>(params string[] sections)
        {
            List<T> list = new List<T>();
            // 引用 Microsoft.Extensions.Configuration.Binder 包
            Configuration.Bind(string.Join(":", sections), list);
            return list;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sections"></param>
        /// <returns></returns>
        public static T get<T>(params string[] sections) where T :new()
        {
            T t = new T();//default(T);
            // 引用 Microsoft.Extensions.Configuration.Binder 包
            Configuration.Bind(string.Join(":", sections), t);
            return t;
        }


        public static string GetPath(string path)
        {
            if (!path.IsNull())
            {
                path = Path.Combine(System.Environment.CurrentDirectory, path);
            }
            return path;
        }
        public static string GetDirPathOrCreate(string path)
        {
            if (!path.IsNull())
            {
                path = Path.Combine(System.Environment.CurrentDirectory, path);
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
            }
            return path;
        }

    }
}
